package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: guozy
 * @Date: 2022/7/31 - 07 - 31 - 9:49
 * @Description: com.itheima.service.impl
 * @version: 1.0
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    /**
     * 保存套餐表Setmeal,和套餐菜品关系表SetmealDish
     * @param setmealDto
     */
    @Override
    public void saveWithSetmealDish(SetmealDto setmealDto) {
        // 1.保存套餐表
        this.save(setmealDto);

        // 2.保存套餐菜品关系表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(item->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 根据ids删除,并且删除套餐菜品关系表
     * @param ids
     */
    @Override
    public void removeWithSetmealDish(List<Long> ids) {
        //查询套餐状态,确定是否可用删除,套餐是否在售卖中
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);
        //数据是否可用
        if (count>0){
            //如果不能删除,则抛出异常
            throw new CustomException("套餐正在售卖中,无法删除");
        }

        //如果可以删除,先删除套餐表中的数据
        this.removeByIds(ids);

        // 删除套餐菜品关系表,通过ids->找出setmeal_id
        LambdaQueryWrapper<SetmealDish> SetmealDishQueryWrapper = new LambdaQueryWrapper<>();
        SetmealDishQueryWrapper.eq(SetmealDish::getId,ids);

        //删除关系表中数据
        setmealDishService.remove(SetmealDishQueryWrapper);
    }
}
